import { isValidVariablePrompt } from "@shared/prompt-editor/utils";
import { useCallback, useEffect, useState } from "react";

export function usePromptEditor(
  currentValue: string | null,
  config?: { needValidate?: boolean },
) {
  const [valid, setValid] = useState<boolean>(true);

  const handleStateChange = useCallback(
    (value: string | null, cb: (value: string | null) => void) => {
      const needValidate = config?.needValidate ?? false;
      const isValid = needValidate ? isValidVariablePrompt(value) : true;

      setValid(isValid);

      cb(value);
    },
    [config?.needValidate],
  );

  useEffect(() => {
    if (!config?.needValidate) return;
    setValid(isValidVariablePrompt(currentValue));
  }, [currentValue, config?.needValidate]);

  return {
    valid,
    handleStateChange,
  };
}
